package com.saic.localfileloader.main;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import com.saic.localfileloader.table.SaicSapACT;
import com.saic.localfileloader.table.SaicSapADJ;
import com.saic.localfileloader.table.SaicSapBUD;
import com.saic.localfileloader.table.TableLoader;

public class FTPUploader {

	public static final int CNT = 100;

	public static void main(String[] args) throws IOException {

		if (args.length < 3) {// check input
			System.out.println("Less params");
			return;
		}

		TableLoader table = null;
		switch (Integer.parseInt(args[0])) {
		case 0:
			table = new SaicSapADJ(args[1], args[2], "\\|");
			break;
		case 1:
			table = new SaicSapBUD(args[1], args[2], "\\|");
			break;
		case 2:
			table = new SaicSapACT(args[1], args[2], "\\|");
			break;
		default:
			System.out.println("Invalidate params");
		}

		DBUtil db = new DBUtil();
		fileFilter(db, table);
	}

	// 一次只能输入一个路径+表名
	public static void fileFilter(DBUtil util, TableLoader table)
			throws IOException {

		File file = new File(table.getLocalPath());
		File[] files = file.listFiles(new FileFilter() {
			public boolean accept(File pathname) {
				if (pathname.getName().endsWith(".txt")
						|| pathname.getName().endsWith(".TXT"))
					return true;
				return false;
			}
		});
		for (File f : files)
			System.out.println(f.getName());
		if (files.length < 1)
			return;
		doAction(util, table, files);
	}

	public static void doAction(DBUtil util, TableLoader table, File[] files)
			throws IOException {
		int cnt = 1;
		String sql = "insert into " + table.getTableName() + "("
				+ table.getHeader() + ")\n";
		for (File f : files) {
			BufferedReader br = new BufferedReader(new InputStreamReader(
					new FileInputStream(f), table.getCharset()));
			String line = null;
			while (null != (line = br.readLine())) {
				if (line.length() < 1)
					continue;
				String tmp = table.getInsertSQL(line);
				if (null == tmp)
					continue;
				sql += tmp;
				cnt++;
				if (cnt % CNT == 0) {
					util.insert(sql);
					sql = "insert into " + table.getTableName() + "("
							+ table.getHeader() + ")\n";
				} else
					sql += " union all \n";
			}
			if (null != sql)
				util.insert(sql.substring(0,
						sql.length() - "  union all".length()));
			br.close();
		}
	}
}
